package com.example.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.domain.Employee;
import com.example.service.IEmployeeService;
import com.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    /**
     * 用户登录
     * @param employee 用户信息
     * @param session 存储用户id
     * @return 返回响应
     */
    @RequestMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session){
        Employee login = employeeService.login(employee);
        session.setAttribute("employee",login.getId());
        return new R(1,login);
    }

    /**
     * 用户退出
     * @param session 删除用户id
     * @return  返回响应
     */
    @RequestMapping("/logout")
    public R logout(HttpSession session){
        session.removeAttribute("employee");
        return new R(1,"退出成功");
    }

    /**
     * 添加员工
     * @param employee 添加员工的信息
     * @param session 存储的数据
     * @return 响应页面的数据
     */
    @RequestMapping
    public R save(@RequestBody Employee employee,HttpSession session){
        employeeService.save(employee,(Long) session.getAttribute("employee"));
        return new R(1,"添加成功");
    }

    /**
     * 分页查询
     * @param page 当前页
     * @param pageSize 每页显示几条
     * @param name 查询的条件
     * @return 响应到页面的数据
     */
    @RequestMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        Page<Employee> page1 = employeeService.page(page, pageSize, name);
        return new R(1,page1);
    }

    /**
     * 启用/禁用功能和修改员工数据共用
     * @param employee 用户修改的信息
     * @param session 用户存储的id
     * @return 响应页面的数据
     */
    @PutMapping
    public R update(@RequestBody Employee employee,HttpSession session){
        employeeService.update(employee,(Long) session.getAttribute("employee"));
        return new R(1);
    }

    /**
     * 修改功能中的回显
     * @param id 修改员工的id
     * @return 回显到页面的数据
     */
    @GetMapping("/{id}")
    public R select(@PathVariable("id")Long id){
        Employee employee = employeeService.select(id);
        return new R(1,employee);
    }
}
